package app

import (
	"database/sql"
	"fmt"
	"github.com/go-redis/redis/v8"
	_ "github.com/go-sql-driver/mysql"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"my-desktop/config"
	"time"
)

func init() {
	initConfig()
	initMySQL()
	initRedis()
}

func initConfig() {
	viper.SetConfigName("properties")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("./config")

	if err := viper.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			fmt.Println("找不到配置文件..")
		} else {
			fmt.Println("配置文件出错..")
		}
	}

	setConfig()
}

func setConfig() {
	// app配置
	config.App.Host = viper.GetString("application.host")
	config.App.Name = viper.GetString("application.name")
	config.App.Port = viper.GetInt("application.port")

	// http配置
	config.Http.Token = viper.GetString("http.token")
	config.Http.TokenPrefix = viper.GetString("http.tokenPrefix")
	config.Http.SshKeyHeader = viper.GetString("http.sshKeyHeader")

	// ssh配置
	config.Ssh.Port = viper.GetInt("ssh.port")

	// JWT配置
	config.Jwt.Secret = viper.GetString("jwt.secret")

	// AES配置
	config.Aes.Secret = viper.GetString("aes.secret")

	// MySQL配置
	config.Mysql.Host = viper.GetString("mysql.host")
	config.Mysql.Port = viper.GetInt("mysql.port")
	config.Mysql.User = viper.GetString("mysql.user")
	config.Mysql.Pwd = viper.GetString("mysql.pwd")
	config.Mysql.DBname = viper.GetString("mysql.dbname")

	// Redis配置
	config.Redis.Host = viper.GetString("redis.host")
	config.Redis.Password = viper.GetString("redis.password")
	config.Redis.Port = viper.GetInt("redis.port")
	config.Redis.DB = viper.GetInt("redis.db")
}

func initMySQL() {
	host := config.Mysql.Host
	port := config.Mysql.Port
	user := config.Mysql.User
	pwd := config.Mysql.Pwd
	dbname := config.Mysql.DBname

	mysqlURL := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=true", user, pwd, host, port, dbname)
	db, err := sql.Open("mysql", mysqlURL)

	//logrus.Info(mysqlURL)

	if err != nil {
		logrus.Error("连接数据库异常")
		panic(err)
	}

	//最大空闲连接数，默认不配置，是2个最大空闲连接
	db.SetMaxIdleConns(5)
	//最大连接数，默认不配置，是不限制最大连接数
	db.SetMaxOpenConns(100)
	// 连接最大存活时间
	db.SetConnMaxLifetime(time.Minute * 3)
	//空闲连接最大存活时间
	db.SetConnMaxIdleTime(time.Minute * 1)

	err = db.Ping()
	if err != nil {
		logrus.Error("数据库无法连接")
		_ = db.Close()
	}
	config.DB = db
}

func initRedis() {
	redisAddr := fmt.Sprintf("%s:%d", config.Redis.Host, config.Redis.Port)
	rdb := redis.NewClient(&redis.Options{
		Addr: redisAddr,
		//Password: config.Redis.Password,
		DB: config.Redis.DB,
	})
	config.RDB = rdb
}
